package com.doudanhua.basecode.jackson.configurer;

import com.doudanhua.basecode.jackson.time.DateTimeConverter;
import com.doudanhua.basecode.jackson.time.NormalDateTimeConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/4 17:23
 */
public class DateTimeJsonConfigurer implements JsonConfigurer {
    private DateTimeConverter dateConverter;

    public DateTimeJsonConfigurer() {
        this.dateConverter = new NormalDateTimeConverter();
    }

    @Override
    public void config(ObjectMapper objectMapper) {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Date.class, new DateModelSerializer(dateConverter));
        module.addDeserializer(Date.class, new DateModelDeserializer(dateConverter));
        module.addSerializer(LocalDateTime.class, new LocalDateTimeModelSerializer(dateConverter));
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeModelDeserializer(dateConverter));
        module.addSerializer(ZonedDateTime.class, new ZonedDateTimeModelSerializer(dateConverter));
        module.addDeserializer(ZonedDateTime.class, new ZonedDateTimeModelDeserializer(dateConverter));

        module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ISO_DATE));
        module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_DATE));

        module.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ISO_TIME));
        module.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ISO_TIME));
        objectMapper.registerModule(module);
    }
}
